package com.bl.car.controller;

import com.bl.car.constants.StateConstant;
import com.bl.car.entity.Car;
import com.bl.car.entity.Driver;
import com.bl.car.entity.Owner;
import com.bl.car.repositiy.CarRepository;
import com.bl.car.repositiy.DriverRepository;
import com.bl.car.repositiy.OwnerRepository;
import com.bl.car.result.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 车辆前端接口
 *
 * @author zhx
 * @create 2017-11-16 13:43
 **/
@RestController
@RequestMapping("/car")
public class CarController {
    @Autowired
    private CarRepository carRepository;

    @Autowired
    private DriverRepository driverRepository;

    @Autowired
    private OwnerRepository ownerRepository;


    //获取要注销的车辆列表
    @PostMapping("/delcars")
    @Transactional
    public Result<List<Car>> delcars(){
        List<Car> byDriverId = carRepository.findByIsEffect(StateConstant.DELETE_TYPE);

        return Result.ok(byDriverId);

    }


    //获取一个业户下面的所有车辆
    @PostMapping("/cars/{id}")
    public Result<List<Car>> getAllCars(@PathVariable("id") String id){
        Owner byUserId = ownerRepository.findByUserId(id);

        List<Driver> byOwnerIdOrderById = driverRepository.findByOwnerIdOrderById(Long.toString(byUserId.getId()));

        if(byOwnerIdOrderById.size()==0){
            return Result.ok(null);

        }

        List<String> tempList = new ArrayList<>();

        for(Driver d:byOwnerIdOrderById){
            tempList.add(Long.toString(d.getId()));
        }

        List<Car> byDriverId = carRepository.findByDriverId(tempList);

        return Result.ok(byDriverId);

    }

    //获取审核的车辆
    @PostMapping("/cars")
    public Result<List<Car>> getAllCars(){
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        List<Car> byDriverId = carRepository.findAll(sort);

        return Result.ok(byDriverId);

    }


    //获取车辆详情
    @PostMapping("/car/{id}")
    public Result<Car> getCarInfo(@PathVariable("id") String id){
        Car byDriverId = carRepository.findByDriverId(id);

        return Result.ok(byDriverId);
    }

    //保存车辆
    @PostMapping("/saveCar/{id}")
    public Result<Car> saveCar(@PathVariable("id") String id, @RequestBody Car car){
        if(StringUtils.isBlank(car.getIsEffect())){
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            car.setApplyTime(df.format(new Date()));

            car.setIsEffect(StateConstant.USER_CHECK);

        }

        car.setDriverId(id);

        carRepository.save(car);
        return Result.ok(car);
    }

}
